package com.ruoyi.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class WechatSignUtil {
    // 与微信后台配置一致的Token
    private static final String TOKEN = "ezpVtEOfDfpLJElTYmcKaBYmpTqTyhYi";

    /**
     * 验证微信签名有效性
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @return 验证结果
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        // 1. 字典序排序参数
        String[] paramArr = {TOKEN, timestamp, nonce};
        Arrays.sort(paramArr);

        // 2. 拼接字符串并SHA1加密
        String content = String.join("", paramArr);
        String generatedSignature = sha1(content);

        // 3. 对比签名
        return generatedSignature != null && generatedSignature.equals(signature);
    }

    private static String sha1(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.getBytes("UTF-8"));
            return byteArrayToHexString(digest);
        } catch (Exception e) {
            throw new RuntimeException("SHA1加密失败: " + e.getMessage());
        }
    }

    // 字节数组转十六进制字符串
    private static String byteArrayToHexString(byte[] bytearray) {
        StringBuilder hexStr = new StringBuilder();
        for (byte b : bytearray) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hexStr.append('0');
            }
            hexStr.append(hex);
        }
        return hexStr.toString().toLowerCase();
    }
}
